# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import scrapy

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


# 取得 Cookies 清单
def get_cookies_dict():
    cookies_str = 'bid=rNchFbn5zzQ; _pk_id.100001.4cf6=17bdd1fb9f64b79f.1706938374.; __yadk_uid=GXTu5SntM45lOggQ1OvmyOCbJCZ1AAyu; __utmc=30149280; __utmz=30149280.1715528984.3.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmc=223695111; __utmz=223695111.1715528984.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utma=30149280.559228270.1705506763.1715528984.1715652978.4; __utma=223695111.1072450681.1706938374.1715528984.1715652978.3; _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1715652978%2C%22https%3A%2F%2Fwww.google.com%2F%22%5D; __gads=ID=0521a4830a82e88e:T=1715528984:RT=1715652979:S=ALNI_MayEbo6MukPKZmCUrYCFiPPIwYbUA; __gpi=UID=00000e195d09b2f4:T=1715528984:RT=1715652979:S=ALNI_MZ6kto_BeWVcNobjZd-0m2MOusXpQ; __eoi=ID=e7d1bc848ffd36cd:T=1715528984:RT=1715652979:S=AA-AfjaWI2tHC8tF8IWj8PwNnCYE; FCNEC=%5B%5B%22AKsRol99cuX7s8r15MTUzJ0LHxwDTpEs_6uAdZDIoNT8WCY6gU7gVQ6JZ-UbIADFVAdVWCWxStaYp7yX4slTA4qtj3vbK9n8AiNDFl1Wwla0wPs5jGZkz3SpUb9dH7NXvHE-8-dCaCDlwug5b_SgUGPC91b1K7HazQ%3D%3D%22%5D%5D; _pk_ses.100001.4cf6=1; dbcl2="280504583:JUGjruDZxSQ"'
    cookies_dict = {}
    for item in cookies_str.split("; "):
        key, value = item.split("=", maxsplit=1)
        cookies_dict[key] = value
    return cookies_dict

# 获取 Cookies
COOKIES_DICT = get_cookies_dict()
# print(COOKIES_DICT)


class DoubanscrapySpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class DoubanscrapyDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request: scrapy.Request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        request.cookies = COOKIES_DICT  # 请求时加入 Cookies 登入信息
        # request.meta = {'proxy': '...'} # 使用代理请求
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)
